#!/usr/bin/python
# coding=utf-8
# author=He

import connect
import sys
import rabbitMq
import time
import json
import timestamp


class Coupon:

    def __init__(self):
        self.db = connect.Connect()
        self.db.select_db(db_name='jbp_06_22')

    def __get_coupon_list_by_shop_id_is_fix(self, shop_id):
        if not shop_id:
            sys.exit(1)
        result = self.db.query_all("SELECT * FROM `juku_shop_seller_coupon` WHERE shop_id = "+shop_id +
                                   " AND `is_shareholder_fix` = '1' AND `is_copy` = '0' AND `top_id` = '0' AND "
                                   "`is_del` = '0' AND end_time > "+str(timestamp.month_start_time))
        return result

    def __get_is_fix_coupon(self):
        result = self.db.query_all("SELECT COUNT(*) num, shop_id FROM juku_shop_seller_coupon WHERE "
                                   "is_shareholder_fix = 1 AND is_copy = 0 AND top_id=0 AND end_time > "
                                   + str(timestamp.month_start_time) +
                                   " AND is_del=0 GROUP BY shop_id")
        return result

    def get_one_coupon(self, coupon_id):
        return self.db.query("SELECT * FROM `juku_shop_seller_coupon` WHERE id = "+coupon_id)

    def get_coupon_list_by_top_id(self, top_id, end_time):
        return self.db.query_row("SELECT * FROM `juku_shop_seller_coupon` "
                                 "WHERE top_id = "+str(top_id)+" AND end_time ="+str(end_time))

    def add_queue(self):
        result = self.__get_is_fix_coupon()
        mq = rabbitMq.RabbitMqService(queue_name='coupon', exchange='coupon')
        for row in result:
            mq.send({'shop_id': row['shop_id'], 'date': int(time.time())}, queue_durable=True, exchange_type='fanout')
        mq.close()
        if mq.is_closed():
            print "fix coupon collect complete"

    def receive(self):
        mq = rabbitMq.RabbitMqService(queue_name='coupon', exchange='coupon')
        channel = mq.get__channel()
        queue_name = exchange = 'coupon'
        exchange_type = 'fanout'
        queue_durable = True
        channel.exchange_declare(exchange=exchange, exchange_type=exchange_type, durable=queue_durable)
        channel.queue_declare(queue=queue_name, passive=False, durable=True, exclusive=False, auto_delete=False)
        channel.queue_bind(queue=queue_name, exchange=exchange)

        def clalback(ch, method, properties, body):
            """
            :param ch: BlockingChannel
            :param method: spec.Basic.Deliver
            :param properties: spec.BasicProperties
            :param body: str or unicode
            """
            param = json.loads(body)
            shop_id = param['shop_id']
            coupon_list = self.__get_coupon_list_by_shop_id_is_fix(shop_id=shop_id)
            for coupon in coupon_list:
                new_data = coupon
                one_info = self.get_coupon_list_by_top_id(top_id=coupon['id'], end_time=timestamp.month_end_time)
                if not one_info:
                    last_one_info = self.get_coupon_list_by_top_id(top_id=coupon['id'],
                                                                   end_time=timestamp.upper_month_end_time)
                    if last_one_info:
                        new_data['pid'] = int(last_one_info[0])
                    else:
                        new_data['pid'] = coupon['id']
                    new_data['top_id'] = coupon['id']
                    new_data['start_time'] = timestamp.month_start_time
                    new_data['end_time'] = timestamp.month_end_time
                    new_data['receive_start_time'] = timestamp.month_start_time
                    new_data['receive_end_time'] = timestamp.month_end_time
                    del new_data['id']
                    self.db.insert('juku_shop_seller_coupon', new_data)

            ch.basic_ack(delivery_tag=method.delivery_tag)
        channel.basic_consume(clalback, queue=queue_name)
        channel.start_consuming()




